/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2018-2021. All rights reserved.
 */

package com.baidu.process.cloud.sdk.util;

import com.baidu.process.cloud.apigateway.sdk.utils.Client;
import com.baidu.process.cloud.apigateway.sdk.utils.Request;
import com.baidu.process.cloud.sdk.auth.vo.SignResult;

import org.apache.http.Header;
import org.apache.http.client.methods.HttpRequestBase;

import java.util.HashMap;
import java.util.Map;

public class SignUtils {
    private static final String SDKSIGNINGSHA256 = "SDK-HMAC-SHA256";

    public static SignResult sign(Request request, String algorithm) throws Exception {
        SignResult result = new SignResult();
        // Sign the request.
        HttpRequestBase signedRequest = Client.sign(request, algorithm);
        Header[] headers = signedRequest.getAllHeaders();
        Map<String, String> headerMap = new HashMap<>();
        for (Header header : headers) {
            headerMap.put(header.getName(), header.getValue());
        }
        result.setUrl(signedRequest.getURI().toURL());
        result.setHeaders(headerMap);

        return result;
    }

    public static SignResult sign(Request request) throws Exception {
        return sign(request, SDKSIGNINGSHA256);
    }
}
